﻿using Acb.Core.Data;
using Acb.Core.Extensions;
using Acb.Dapper;
using Acb.Dapper.Domain;
using Dapper;
using OAuth.Server.Domain.Entities;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace OAuth.Server.Domain
{
    public class GrantRepository : DapperRepository<TGrant>
    {
        public async Task<IEnumerable<TGrant>> QueryBySubjectIdAsync(string subjectId)
        {
            var type = typeof(TGrant);
            var sql = $"SELECT {type.Columns()} FROM [{type.PropName()}] WHERE [SubjectId]=@subjectId";
            sql = Connection.FormatSql(sql);
            return await Connection.QueryAsync<TGrant>(sql, new { subjectId });
        }

        public async Task<int> DeleteBySubjectIdAsync(string subjectId, string clientId, string type = null)
        {
            var modelType = typeof(TGrant);
            SQL sql = $"DELETE FROM [{modelType.PropName()}] WHERE [ClientId]=@clientId AND [SubjectId]=@subjectId";
            if (!string.IsNullOrWhiteSpace(type))
            {
                sql += "AND [Type]=@type";
            }

            var t = Connection.FormatSql(sql.ToString());
            return await Connection.ExecuteAsync(t, new { subjectId, clientId, type });
        }
    }
}
